<template>
  <div class="serial-number-blockly">
    <div class="rule-editor-header">
      <div class="rule-editor-header-preview">
        <el-tag
          v-for="tag in widgetList"
          :key="tag.tagId"
          :closable="limitTagCompute"
          :type="tag.tagId"
          @close="handleDeleteByTagId(tag.tagId)"
        >
          {{ tag.data.label }}
        </el-tag>
      </div>
    </div>
    <div class="rule-editor-content">
      <el-text type="info" size="small"> 拖动左上角的小圆点可对其排序</el-text>
      <VueDraggable
        :list="widgetList"
        :force-fallback="true"
        :animation="200"
        handle=".drag-icon"
        @end="onDragEnd"
        class="m-t-8px"
        item-key="tagId"
      >
        <template #item="{ element, index }">
          <div
            class="mb-4px flex flex-col gap-4px border border-gray-2 border-rounded rounded border-solid p-8px"
          >
            <!-- 操作按钮区 -->
            <div class="m--8px m-b-4px flex flex-row items-center justify-between bg-gray-1 p-8px">
              <el-tooltip content="拖动排序">
                <Icon icon="ic:round-drag-indicator" class="drag-icon cursor-move" />
              </el-tooltip>
              <el-tooltip>
                <span>{{ element.label }}</span>
              </el-tooltip>
              <el-tooltip content="删除">
                <Icon
                  icon="ep:delete"
                  class="cursor-pointer text-red-5"
                  v-if="widgetList.length > 1"
                  @click="handleDelete(index)"
                />
              </el-tooltip>
            </div>

            <component
              :is="getComponent(element.name)"
              v-model="element.data"
              :key="generateUUID()"
              @update:data="updateWidgetData(index, $event)"
            />
            <!-- 内容区 -->
            <slot :element="element" :index="index"></slot>
          </div>
        </template>
      </VueDraggable>
    </div>

    <div class="rule-editor-header">
      <el-tooltip
        :disabled="limit < 1"
        :content="`最多添加${limit}个`"
        v-click-outside="onClickOutside"
        text
      >
        <el-button
          type="primary"
          plain
          class="m-t-4px w-full"
          virtual-triggering
          v-click-outside="onClickOutside"
          v-popover="popoverRef"
          :disabled="limitCompute"
        >
          <Icon icon="ep:plus" />
          <span>添加</span>
        </el-button>
      </el-tooltip>

      <el-popover
        ref="popoverRef"
        trigger="click"
        class="rule-edit-popover"
        title=""
        width="270px"
        height="200"
        :show-arrow="true"
        placement="bottom-end"
      >
        <div class="rule-edit-popover-content">
          <div class="flex gap-2 mt-4">
            <el-tag type="primary" @click="addSnRule(fixedStrModel())">固定字符</el-tag>
          </div>

          <div class="flex gap-2 mt-4">
            <el-tag type="success" @click="addSnRule(SnDateModel())">时间格式</el-tag>
          </div>

          <div class="flex gap-2 mt-4">
            <el-tag type="warning" @click="addSnRule(SnNumberModel())">编号规则</el-tag>
          </div>
<!--          <div class="flex gap-2 mt-4">-->
<!--            <el-tag type="info" @click="addSnRule(SnTableFieldsModel())">引用字段</el-tag>-->
<!--          </div>-->
        </div>
      </el-popover>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, unref, computed } from 'vue'
import { ClickOutside as vClickOutside } from 'element-plus'
import SnFixedStr from '@/components/FormCreate/src/components/SerialNumber/SnFixedStr.vue'
import SnDate from '@/components/FormCreate/src/components/SerialNumber/SnDate.vue'
import SnTableFields from '@/components/FormCreate/src/components/SerialNumber/SnTableFields.vue'
import SnNumber from '@/components/FormCreate/src/components/SerialNumber/SnNumber.vue'
import VueDraggable from 'vuedraggable'
import { cloneDeep } from 'lodash-es'
import {
  getFormTitle,
  padZero,
  SnWidgetItemType
} from '@/components/FormCreate/src/config/SerialNumber/UseSerialNumberRule'
import { generateUUID } from '@/utils'
import { dateUtil } from '@/utils/dateUtil'
import {useApprovalDesignerStore} from "@/store/modules/dsgn/ApprovalDesigner";

defineOptions({ name: 'SerialNumberEditor' })

const popoverRef = ref()

const limit = ref(10)

const props = withDefaults(
  defineProps<{
    modelValue: SnWidgetItemType[]
  }>(),
  {
    modelValue: () => [] as SnWidgetItemType[]
  }
)
//
// const designerStore = useApprovalDesignerStore()
//
//
// const snInject = ref(props.formCreateInject)
// const currentValue = ref(props.modelValue)
//
// const currentApi = computed(() => props.formCreateInject.api)


// 定义组件映射
const componentMap = {
  SnFixedStr,
  SnDate,
  SnNumber,
  SnTableFields
}

const widgetList = ref<SnWidgetItemType>(props.modelValue)

const limitCompute = computed(() => {
  return limit.value > 0 && widgetList.value.length >= limit.value
})
const limitTagCompute = computed(() => {
  return limit.value > 0 && widgetList.value.length > 1
})

// const widgetListTag=cloneDeep(unref(widgetList))
const fixedStrModel = (option: any) => {


  const formTitle = getFormTitle()
  return {
    tagId: generateUUID(),
    name: 'SnFixedStr',
    label: '固定字符',
    data: {
      label: formTitle,
      value: formTitle
    }
  }
}

const sbDateLabel = dateUtil().format('YYYYMMDD')
const SnDateModel = (option: any) => {
  return {
    tagId: generateUUID(),
    name: 'SnDate',
    label: '时间格式',
    data: {
      label: sbDateLabel,
      value: 'YYYYMMDD'
    }
  }
}

const SnNumberModel = (option: any) => {
  const snObj = {
    dataType: 1,
    complementZero: 4,
    resetCycle: 6,
    begin: 1
  }

  return {
    tagId: generateUUID(),
    name: 'SnNumber',
    label: '编号规则',
    data: {
      label: padZero(snObj.begin, snObj.complementZero),
      value: snObj
    }
  }
}

const SnTableFieldsModel = (option: any) => {
  return {
    tagId: generateUUID(),
    name: 'SnTableFields',
    label: '引用字段',
    data: ''
  }
}

//添加规则
const addSnRule = (type: SnWidgetItemType) => {

  widgetList.value.push(type)
  popoverRef.value.hide()
}

const LimitCompute = computed(() => {
  return limit.value > 0 && widgetList.value.length >= limit.value
})

const handleDelete = (index: number) => widgetList.value.splice(index, 1)

/** 根据 tagId 删除 */
const handleDeleteByTagId = (tagId: string) => {
  const index = widgetList.value.findIndex((item) => item.tagId === tagId)
  widgetList.value.splice(index, 1)
}
/** 点击弹出框外隐藏 */
const onClickOutside = () => {
  unref(popoverRef).popperRef?.delayHide?.()
}

//
onMounted(() => {
  // widgetList.value=[]



  updateParentData()
})

const getComponent = (widgetName: string) => {
  return componentMap[widgetName]
}

const emit = defineEmits(['update:modelValue'])

// 监听子组件的更新，更新父组件的数据
const updateParentData = () => {
  emit('update:modelValue', widgetList.value)
}

const updateWidgetData = (index, newData) => {
  widgetList.value[index].data = newData
  //监听子组件的更新，更新父组件的数据
  // emit('update:modelValue', widgetList.value)
  updateParentData()
}

const onDragEnd = () => {
  updateParentData()
  // console.log('新的顺序:', choosePattern.value)
}

// //监听 widgetList 的变化
// watch(
//   widgetList,
//   (newVal, oldVal) => {
//
//     updateParentData()
//     console.log('widgetList 变动了:', newVal, '旧值:', oldVal)
//   },
//   { immediate: true, deep: true }
// )
</script>

<style scoped lang="scss">
.serial-number-blockly {
  width: 100%;
}

.rule-editor-list {
  li {
    list-style-type: none;
  }
}

.rule-edit-popover {
  width: 100%;
}

.rule-editor-header-preview {
  margin-bottom: 10px;
  border: 1px solid #d9d9d9;
  padding: 0 5px 5px 5px;
  border-radius: 4px;
}

.rule-edit-popover-content {
  width: 100%;

  .el-tag {
    cursor: pointer;
  }
}

.rule-edit-options {
  border: 1px solid #2e73ff;
  border-radius: 4px;
  width: 100%;
}

.drag-icon {
  cursor: pointer;
  user-select: none; /* 禁用文本选择 */
  -webkit-user-drag: none; /* Safari */
}
</style>
